package com.theyeasy.dvmini.pc.controller;

import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.drew.imaging.jpeg.JpegMetadataReader;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.MetadataException;
import com.drew.metadata.exif.ExifDirectory;
import com.theyeasy.dvmini.util.CommonUtil;
import com.theyeasy.dvmini.vo.Vo_msg;

@Controller
@RequestMapping("/upload")
public class UploadController extends BaseController {

    /**
     * 上传图片
     * 
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/UploadImg", method = RequestMethod.POST)
    public @ResponseBody Object UploadImg(HttpServletRequest request, MultipartFile file) throws IOException {
        if (file == null || file.isEmpty())
            return new Vo_msg(-1, "上传文件不能为空");
        String returnPath = ""; // 需要返回的图片相对路径

        String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/res/upload");
        String imageType = "posttemplet";
        File path = new File("");
        String fileName = file.getOriginalFilename();
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        System.out.println("fileExt:" + fileExt);
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
        try {
            // 判断文件夹是否存在。如果不存在则创建文件夹
            String ctxPath = realPath + "/" + imageType;
            File filepath = new File(ctxPath);
            if (!filepath.exists()) {
                filepath.mkdirs();
            }
            BufferedImage bi = null;
            path = new File(ctxPath + "/" + newFileName);
            System.out.println("path=" + path);
            BufferedImage src = ImageIO.read(file.getInputStream());
            int src_width = src.getWidth();
            int src_height = src.getHeight();

            int angel = getRotateAngleForPhoto(file.getInputStream());
            if (angel != 0) {
                /*
                 * BufferedImage src = ImageIO.read(file.getInputStream()); int src_width = src.getWidth(null); int
                 * src_height = src.getHeight(null);
                 */
                Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);
                bi = new BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D g2 = bi.createGraphics();
                g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);
                g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
                g2.drawImage(src, null, null);
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(bi, fileExt, os);
                FileCopyUtils.copy(os.toByteArray(), path); // 把图片复制到本地
                os.close();
            } else {
                FileCopyUtils.copy(file.getBytes(), path); // 把图片复制到本地
            }
            // 图片压缩
            if (src_width != 640) {
                int height = (src_height * 640) / src_width;
                System.out.println("scaleheight:" + height);
                com.theyeasy.dvmini.util.ImageUtil.scale2(ctxPath + "/" + newFileName, ctxPath + "/" + newFileName,
                        height, 640, false);

            }
            returnPath = "/dvmini/res/upload/" + imageType + "/" + newFileName;
            System.out.println(returnPath);

            /* } */
        } catch (Exception e) {
            e.printStackTrace();
            return new Vo_msg(-1, "上传失败，数据异常");
        }
        System.out.println("图片path=" + path);
        return new Vo_msg(0, returnPath);
    }

    /**
     * 图片翻转时，计算图片翻转到正常显示需旋转角度
     */
    public int getRotateAngleForPhoto(InputStream stream) {

        int angel = 0;
        Metadata metadata;

        try {
            metadata = JpegMetadataReader.readMetadata(stream);
            Directory directory = metadata.getDirectory(ExifDirectory.class);
            if (directory.containsTag(ExifDirectory.TAG_ORIENTATION)) {
                // Exif信息中方向
                int orientation = directory.getInt(ExifDirectory.TAG_ORIENTATION);
                // 原图片的方向信息
                if (6 == orientation) {
                    // 6旋转90
                    angel = 90;
                } else if (3 == orientation) {
                    // 3旋转180
                    angel = 180;
                } else if (8 == orientation) {
                    // 8旋转90
                    angel = 270;
                }
            }
        } catch (JpegProcessingException e) {
        } catch (MetadataException e) {
        }
        return angel;
    }

    /**
     * 计算旋转参数
     */
    public static Rectangle CalcRotatedSize(Rectangle src, int angel) {
        // if angel is greater than 90 degree,we need to do some conversion.
        if (angel > 90) {
            if (angel / 9 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }

        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);

        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_width));
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_height));
        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        return new java.awt.Rectangle(new Dimension(des_width, des_height));
    }

    

    /**
     * 上传图片
     * 
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/NewUploadImg", method = RequestMethod.POST)
    public @ResponseBody Object NewUploadImg(HttpServletRequest request) throws IOException {
 

        String returnPath = ""; // 需要返回的图片相对路径
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/res/upload");
        System.out.println(CommonUtil.getTime());
        String uploadType = null;
        String imageType = "UE";
        File path = new File("");
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile mf = entity.getValue();
            String fileName = mf.getOriginalFilename();
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            uploadType = request.getParameter("uploadType"); // 判断是单个上传还是批量上传
            String newFileName = "";
            // 抽奖人名单
            if ("employees".equals(imageType)) {
                boolean b = fileName.contains(".jpg");
                if (!b) {
                    return "上传文件扩展名是不允许的扩展名。只允许jpg格式。!";
                }
                newFileName = fileName;
            } else {
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
            }
            try {
                // 判断文件夹是否存在。如果不存在则创建文件夹
                String ctxPath = realPath + "/" + imageType;
                File file = new File(ctxPath);
                if (!file.exists()) {
                    file.mkdirs();
                }
                BufferedImage bi = null;
                path = new File(ctxPath + "/" + newFileName);
                System.out.println("path=" + path);
                int angel = getRotateAngleForPhoto(mf.getInputStream());
                if (angel != 0) {
                    BufferedImage src = ImageIO.read(mf.getInputStream());
                    int src_width = src.getWidth(null);
                    int src_height = src.getHeight(null);
                    Rectangle rect_des = CalcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);

                    bi = new BufferedImage(rect_des.width, rect_des.height, BufferedImage.TYPE_INT_RGB);
                    Graphics2D g2 = bi.createGraphics();
                    g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);
                    g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);

                    g2.drawImage(src, null, null);
                    ByteArrayOutputStream os = new ByteArrayOutputStream();
                    ImageIO.write(bi, fileExt, os);
                    FileCopyUtils.copy(os.toByteArray(), path); // 把图片复制到本地
                    os.close();
                } else {
                    FileCopyUtils.copy(mf.getBytes(), path); // 把图片复制到本地
                }
 
                returnPath = "http://mini.weiyisz.com/dvmini/res/upload/" + imageType + "/" + newFileName;
                System.out.println(returnPath);
                /* } */
            } catch (Exception e) {
                e.printStackTrace();
                return "<script>alert('上传失败');parent.$('#AddFile').attr('uploadstatus','true').trigger('click');</script>";
            }
        }

        // if (uploadType != null) { // 批量上传
        String result = "{\"name\":\"\", \"originalName\": \"\", \"size\":\"1000\", \"state\": \"SUCCESS\", \"type\": \"\", \"url\": \""
                + returnPath + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        return result;
        
    }

}
